import requests, json
import base64
import urllib

class BDapi():
    def __init__(self) -> None:
        self.API_KEY = "iK60YOVmo7p9x6wZ5Dwh8t3W"
        self.SECRET_KEY = "71Zf8PHOaRXOIwzVHCt2LnLOpFY2GrqU"

    def get_access_token(self):
        """
        使用 AK，SK 生成鉴权签名（Access Token）
        :return: access_token，或是None(如果错误)
        """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
        return str(requests.post(url, params=params).json().get("access_token"))

    def audit_mes(self, mes):
        url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + self.get_access_token()

        payload = 'text=' + mes
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload)
        data = json.loads(response.text)
        print(data)

        if data['conclusion'] == '合规':
            return mes
        else:
            return "内容不合法"

    def get_file_content_as_base64(self, path, urlencoded=False):
        """
        获取文件base64编码
        :param path: 文件路径
        :param urlencoded: 是否对结果进行urlencoded
        :return: base64编码信息
        """
        with open(path, "rb") as f:
            content = base64.b64encode(f.read()).decode("utf8")
            if urlencoded:
                content = urllib.parse.quote_plus(content)
        return content

    # 身份证验证
    def idcard(self, picurl):

        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + self.get_access_token()

        # image 可以通过 get_file_content_as_base64("C:\fakepath\1.png",True) 方法获取
        payload = 'id_card_side=front&image=%s&detect_ps=false&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false' % (
            self.get_file_content_as_base64(picurl, True))
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload)

        print(response.text)
        # return response
        obj = json.loads(response.text)
        if obj["idcard_number_type"] == 1:
            print("是身份证")
            name = obj["words_result"]["姓名"]["words"]
            idcard = obj["words_result"]["公民身份号码"]["words"]
            return {"name": name, "idcard": idcard}
        else:
            print("非身份证")
            return None

bdapi = BDapi()

if __name__ == '__main__':
    # mes = bdapi.audit_mes("我是中国人")
    # print(mes)

    # print(bdapi.get_file_content_as_base64("E:/0/myId.jpg", True))
    bdapi.idcard("E:/0/myId.jpg")
